<template>
  <div class="group-list">
    <div class="search-form">
      <a-form :model="searchForm" layout="inline">
        <a-row :gutter="10">
          <a-col :span="20" style="text-align: right">
            <a-row :gutter="16">
              <a-col :span="6"
                ><a-form-item field="nick" label="群名称">
                  <a-input
                    v-model="searchForm.nick"
                    placeholder="请输入群名称"
                    allow-clear
                    @change="handleSearch"
                  /> </a-form-item
              ></a-col>
              <a-col :span="6"
                ><a-form-item field="tags" label="标签">
                  <a-input
                    v-model="searchForm.tags"
                    placeholder="请输入标签"
                    allow-clear
                    @change="handleSearch"
                  /> </a-form-item
              ></a-col>
              <a-col :span="4"
                ><a-form-item field="issave" label="保存群信息">
                  <a-select
                    v-model="searchForm.issave"
                    placeholder="请选择"
                    allow-clear
                    @change="handleSearch"
                  >
                    <a-option :value="1">开启</a-option>
                    <a-option :value="0">关闭</a-option>
                  </a-select>
                </a-form-item></a-col
              >
              <a-col :span="4"
                ><a-form-item field="isauto" label="自动处理">
                  <a-select
                    v-model="searchForm.isauto"
                    placeholder="请选择"
                    allow-clear
                    @change="handleSearch"
                  >
                    <a-option :value="1">开启</a-option>
                    <a-option :value="0">关闭</a-option>
                  </a-select>
                </a-form-item></a-col
              >
              <a-col :span="4"
                ><a-form-item field="isreceive" label="接收群发">
                  <a-select
                    v-model="searchForm.isreceive"
                    placeholder="请选择"
                    allow-clear
                    @change="handleSearch"
                  >
                    <a-option :value="1">接收</a-option>
                    <a-option :value="0">不接收</a-option>
                  </a-select>
                </a-form-item></a-col
              >
            </a-row>
          </a-col>
          <a-col flex="88px" style="text-align: right">
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleSearch">搜索</a-button>
                <a-button style="margin-left: 8px" @click="handleReset"
                  >重置</a-button
                >
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div style="padding-bottom: 10px">
      <a-space>
        <a-button
          type="primary"
          status="danger"
          :disabled="selectedKeys.length === 0"
          @click="handleQuitGroup"
        >
          批量退群
        </a-button>
      </a-space>
    </div>
    <a-table
      row-key="wxid"
      :data="groupList"
      :columns="columns"
      :loading="loading"
      :pagination="{
        total: count,
        current: current,
        pageSize: pageSize,
        showTotal: true,
        showPageSize: true,
      }"
      :row-selection="{
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      }"
      v-model:selectedKeys="selectedKeys"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #avatar="{ record }">
        <a-avatar @click="handleGetInfo(record)">
          <img alt="avatar" :src="record.avatarMaxUrl" />
        </a-avatar>
      </template>
      <template #issave="{ record }">
        <a-switch
          :model-value="record.issave"
          @change="(value) => handleSaveChange(record, Boolean(value))"
        />
      </template>
      <template #isauto="{ record }">
        <a-switch
          :model-value="record.isauto"
          @change="(value) => handleAutoChange(record, Boolean(value))"
        />
      </template>
      <template #isreceive="{ record }">
        <a-switch
          :model-value="record.isreceive"
          @change="(value) => handleIsreceive(record, Boolean(value))"
        />
      </template>
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag
            v-for="tag in record.tags"
            :key="tag"
            closable
            @close="handleRemoveTag(record, tag)"
          >
            {{ tag }}
          </a-tag>
          <a-input
            v-if="showInput && editingWxid === record.wxid"
            ref="inputRef"
            v-model="inputVal"
            :style="{ width: '90px' }"
            size="mini"
            @keyup.enter="handleAddTag(record)"
            @blur="handleAddTag(record)"
          />
          <a-tag
            v-else
            :style="{
              backgroundColor: 'var(--color-fill-2)',
              border: '1px dashed var(--color-fill-3)',
              cursor: 'pointer',
            }"
            @click="handleEditTag(record)"
          >
            <template #icon>
              <icon-plus />
            </template>
          </a-tag>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { IconPlus } from '@arco-design/web-vue/es/icon';
  import { Message, Modal } from '@arco-design/web-vue';
  import {
    getGroupList,
    editGroup,
    getGroupInfo,
    quitGroup,
  } from '@/api/weixin';
  import type { TableColumnData } from '@arco-design/web-vue';

  const props = defineProps<{
    wxid: string;
  }>();

  // 分页相关
  const current = ref(1);
  const pageSize = ref(10);
  const count = ref(0);
  const loading = ref(false);
  const groupList = ref([]);
  const selectedKeys = ref<string[]>([]);
  // 搜索表单数据
  const searchForm = ref({
    nick: '',
    tags: '',
    issave: undefined as undefined | number,
    isauto: undefined as undefined | number,
    isreceive: undefined as undefined | number,
  });

  const columns: TableColumnData[] = [
    {
      title: '头像',
      slotName: 'avatar',
      width: 80,
      align: 'center',
    },
    {
      title: '群名称',
      dataIndex: 'nick',
      width: 200,
    },
    {
      title: '群ID',
      dataIndex: 'wxid',
      width: 180,
    },
    {
      title: '群成员数',
      dataIndex: 'groupMemberNum',
      width: 100,
      align: 'center',
    },
    {
      title: '群管理员',
      dataIndex: 'goupManger',
      width: 120,
    },
    {
      title: '标签',
      slotName: 'tags',
      width: 200,
    },
    {
      title: '保存群消息',
      slotName: 'issave',
      width: 100,
      align: 'center',
    },
    {
      title: '群发开关',
      slotName: 'isreceive',
      width: 100,
      align: 'center',
    },
    {
      title: '自动处理',
      slotName: 'isauto',
      width: 100,
      align: 'center',
    },
  ];

  // 获取群聊列表
  const fetchGroupList = async (wxid: string) => {
    loading.value = true;
    try {
      const res: any = await getGroupList(wxid, {
        page: current.value,
        pageSize: pageSize.value,
        field: {
          nick: searchForm.value.nick,
          issave: searchForm.value.issave,
          tags: searchForm.value.tags,
          isauto: searchForm.value.isauto,
          isreceive: searchForm.value.isreceive,
        },
      });
      if (res.code === 20000) {
        count.value = res.data.count;
        groupList.value = res.data.list;
      } else {
        Message.error(res.data.msg || '获取群聊列表失败');
      }
    } catch (error) {
      console.error('获取群聊列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 处理页码变化
  const handlePageChange = async (page: number) => {
    current.value = page;
    await fetchGroupList(props.wxid);
  };

  // 处理每页条数变化
  const handlePageSizeChange = async (size: number) => {
    pageSize.value = size;
    current.value = 1;
    await fetchGroupList(props.wxid);
  };

  // 处理保存群消息开关
  const handleSaveChange = async (record: any, value: boolean) => {
    try {
      const res: any = await editGroup({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          issave: value ? 1 : 0,
        },
      });
      if (res.code === 20000) {
        Message.success('设置成功');
        await fetchGroupList(props.wxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
    }
  };
  const handleIsreceive = async (record: any, value: boolean) => { 
    try {
      const res: any = await editGroup({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          isreceive: value,
        },
      });

      if (res.code === 20000) {
        Message.success('设置成功');
        // 刷新列表数据
        await fetchGroupList(props.wxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
      // 如果失败，恢复开关状态
      record.isconfirmpay = !value;
    }
  };
  // 处理自动处理开关
  const handleAutoChange = async (record: any, value: boolean) => {
    try {
      const res: any = await editGroup({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          isauto: value ? 1 : 0,
        },
      });
      if (res.code === 20000) {
        Message.success('设置成功');
        await fetchGroupList(props.wxid);
      } else {
        Message.error(res.msg || '设置失败');
      }
    } catch (error) {
      Message.error('设置失败');
    }
  };

  // 搜索处理
  const handleSearch = () => {
    current.value = 1; // 重置页码
    fetchGroupList(props.wxid);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.value = {
      nick: '',
      tags: '',
      issave: undefined,
      isauto: undefined,
      isreceive: undefined,
    };
    current.value = 1;
    fetchGroupList(props.wxid);
  };

  // 标签编辑相关变量
  const inputRef = ref<HTMLTextAreaElement | null>(null);
  const showInput = ref(false);
  const inputVal = ref('');
  const editingWxid = ref('');

  // 开始编辑标签
  const handleEditTag = (record: any) => {
    editingWxid.value = record.wxid;
    showInput.value = true;

    nextTick(() => {
      if (inputRef.value) {
        inputRef.value.focus();
      }
    });
  };
  // 添加标签
  const handleAddTag = async (record: any) => {
    if (inputVal.value) {
      try {
        // 获取当前标签数组
        const currentTags = [...(record.tags || [])];
        // 添加新标签
        if (!currentTags.includes(inputVal.value)) {
          currentTags.push(inputVal.value);

          const res: any = await editGroup({
            mywxid: props.wxid,
            wxid: record.wxid,
            field: {
              tags: currentTags,
            },
          });

          if (res.code === 20000) {
            Message.success('添加标签成功');
            await fetchGroupList(props.wxid);
          } else {
            Message.error(res.msg || '添加标签失败');
          }
        }
      } catch (error) {
        Message.error('添加标签失败');
      }
    }
    inputVal.value = '';
    showInput.value = false;
    editingWxid.value = '';
  };

  // 移除标签
  const handleRemoveTag = async (record: any, tag: string) => {
    try {
      const currentTags = record.tags.filter((t: string) => t !== tag);

      const res: any = await editGroup({
        mywxid: props.wxid,
        wxid: record.wxid,
        field: {
          tags: currentTags,
        },
      });

      if (res.code === 20000) {
        Message.success('删除标签成功');
        await fetchGroupList(props.wxid);
      } else {
        Message.error(res.msg || '删除标签失败');
      }
    } catch (error) {
      Message.error('删除标签失败');
    }
  };

  const handleGetInfo = async (record: any) => {
    try {
      const res: any = await getGroupInfo({
        mywxid: props.wxid,
        wxid: record.wxid,
      });
      if (res.code === 20000) {
        // friendInfo.value = JSON.stringify(res.data.result, null, 2);
        await fetchGroupList(props.wxid);
      } else {
        Message.error(res.msg || '获取微信信息失败');
      }
    } catch (error) {
      Message.error('获取微信信息失败');
    }
  };

  const handleQuitGroup = async () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('请选择要退出的群');
      return;
    }

    const handleConfirm = async () => {
      try {
        const res: any = await quitGroup({
          mywxid: props.wxid,
          wxids: selectedKeys.value,
        });

        if (res.code === 20000) {
          Message.success('批量删除成功');
          selectedKeys.value = []; // 清空选中项
          await fetchGroupList(props.wxid);
        } else {
          Message.error(res.msg || '批量删除失败');
        }
      } catch (error) {
        Message.error('批量删除失败');
      }
    };

    Modal.warning({
      title: '删除确认',
      content: `确定要退出选中的 ${selectedKeys.value.length} 个群吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: handleConfirm,
    });
  };

  // 监听wxid变化获取群聊列表
  watch(
    () => props.wxid,
    async (newVal) => {
      if (newVal) {
        current.value = 1;
        await fetchGroupList(newVal);
      }
    },
    { immediate: true }
  );
</script>

<style scoped>
  .group-list {
    width: 100%;
  }
  .search-form {
    padding: 16px;
    background-color: var(--color-bg-2);
    border-radius: 4px;
  }

  :deep(.arco-form-item-layout-inline) {
    margin-right: 16px;
    margin-bottom: 16px;
  }
</style>
